<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-02 14:42:17
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;

use App\Http\Services\Purchase\StorageService;
use App\Http\Services\Service;
use App\Repositories\ProOutsourcingDeliveryDetailRepository;
use App\Repositories\ProOutsourcingDeliveryRepository;

/**
 * @property ProOutsourcingDeliveryRepository $repository
 * @property ProOutsourcingDeliveryDetailRepository $details 
 */
class OutsourcingDeliveryService extends Service
    {
    public function boot(
        ProOutsourcingDeliveryRepository $repository,
        ProOutsourcingDeliveryDetailRepository $details,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        // DB::enableQueryLog();
        $data = $this->details->condition(request())->getGrid();
        // dd(DB::getQueryLog());

        return $data;
        }

    public function raws()
        {
        $code  = request("code");
        $gdata = $this->repository->whereCode($code)->getOne();

        $list = $gdata->raws;
        return $list;
        }
    public function pack()
        {
        $detail_id     = request("detail_id");
        $gdata         = $this->details->whereId($detail_id)->getOne();
        $list          = $gdata->pack;
        $gdata['rate'] = 100;
        $list[]        = $gdata;
        return $list;
        }
    public function info()
        {
        // DB::enableQueryLog();
        $data = $this->repository->condition(request())->getOne();
        // dd(DB::getQueryLog());

        return $data;
        }

    protected function save()
        {
        $data    = request()->toArray();
        $details = $data['details'];
        unset($data['details']);
        if (($data['id'] ?? false) && is_numeric($data['id']) && $data['id'] > 0) {
            $gdata = $this->repository->whereId($data['id'])->first();
            if ($gdata->status_id != 0) {
                fail("单据状态{$gdata->status->name},保存失败！");
                }
            }

        $gdata = $this->repository->autosave($data);

        array_filter($details, function ($detail) use ($gdata)
            {
            $detail['code']             = $gdata->code;
            $detail['price']            = $gdata['price'];
            $detail['amount']           = $gdata['price'] * $detail['quantity'];
            $detail['outfactory_id']    = $gdata->outfactory_id;
            $detail['process_route_id'] = $gdata->process_route_id;
            $detail['billdate']         = $gdata->billdate;
            $detail                     = $this->details->autosave($detail);
            $detail->packs->filter(function ($pack) use ($gdata)
                {
                $pack->main_id    = $gdata->id;
                $pack['billdate'] = $gdata->billdate;
                $pack->save();
                });
            });

        $this->saveCar($gdata);
        // $this->handStorage($gdata, $notNeedOutStorage, $needReOutStorage);
        return $gdata;
        }
    private function saveCar($allot_data)
        {
        $allot_data->details->filter(function ($row) use ($allot_data)
            {
            if ($allot_data->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();

            if ($allot_data->car_id > 0)
                $row->addCarItem($row->location->name, $row->outfactory->name, $allot_data->car_id, $row->code);
            });
        }

    protected function audit()
        {
        $main_codes = $this->details->whereIn("id", $this->getRequestIds())->pluck("code");
        $this->repository->whereIn("code", $main_codes)->get()->filter(function ($v)
            {
            $this->repository->audit($v);
            });
        }
    protected function noaudit()
        {
        $main_codes = $this->details->whereIn("id", $this->getRequestIds())->pluck("code");
        $this->repository->whereIn("code", $main_codes)->get()->filter(function ($v)
            {
            $this->repository->noaudit($v);
            });
        }
    public function handStorage($gdata, $notNeedOutStorage = [], $needReOutStorage = [])
        {
        $gdata->details->filter(function ($v) use ($gdata, $notNeedOutStorage, $needReOutStorage)
            {
            $v->price            = $gdata->price;
            $v->process_route_id = $gdata->process_route_id;
            $v->outfactory_id    = $gdata->outfactory_id;
            $v->billdate         = $gdata->billdate;
            //变了数量，先取消出库
            if (in_array($v->id, $needReOutStorage)) {
                $v->noaddStorage("new_mpc_detail");
                $v->nosubStorage()->nouseStorage();
                }
            //什么都没有变，不做处理。新增的，或者变了数量的，扣库新增
            if (!in_array($v->id, $notNeedOutStorage)) {

                $v->useStorage("委外发货")->subStorage();
                //获取加工厂的库位
                $newlocation_id = $gdata->outfactory->getLocation(1);
                //新增库存,保存汇总库存ID
                $v->summary_storage_id = $v->mergeWhere(['location_id' => $newlocation_id])
                    ->addStorage("委外入库", $v->code, 0, 0, "new_mpc_detail")->summary_storage_id;
                $v->save();
                }
            });
        }
    protected function delete()
        {
        $codes = array_map(function ($v)
            {
            return $v['code'];
            }, request("removeRecords"));

        return $this->repository->whereIn("code", $codes)->get()->filter(function ($v)
            {
            if ($v->status_id != 0) {
                fail("单据状态{$v->status->name},删除失败！");
                }
            $v->details?->filter(function ($vv)
                {
                $vv->delete();
                });
            $v->packs?->filter(function ($vv)
                {
                $vv->delete();
                });
            $v->raws?->filter(function ($vv)
                {
                $vv->delete();
                });
            $v->delete();
            });
        }

    public function printReport()
        {
        $codes = $this->details->whereIn("id", $this->getRequestIds())->pluck("code");
        $list  = $this->details->whereCode($codes[0])
            ->setRelation(['location' => ['department'], 'material', 'outfactory', 'creator'])
            ->getList()->map(function ($v, $k)
                {
                $v['hanghao'] = $k + 1;
                return $v;
                });
        return createReport($list->toArray());
        }
    }